import math
from datetime import datetime
import codecs
from flask_wtf.file import FileRequired, FileAllowed

from app.libs.ParseDocx import ParseDocx, ParseDoc, ParsePDF
from app.config.secure import DOC_PATH, SELFDOC_PATH
from app.models.order_info import order_info
from app.models.writer_orders import writer_orders
from app.taobao_api.get_order_status import Order_Status
from app.validators.base import BaseForm as Form, SearchForm
from wtforms import DecimalField, StringField, IntegerField, FloatField, FieldList, TextField, TextAreaField, FileField
from wtforms.validators import length, DataRequired, Length
from wtforms import ValidationError
from flask import g
import re
from app.taobao_api import config, get_order_status
from app import redisclient
from app.validators.filebase import FileBaseForm


class ArticleSubmitByUploadForm(Form):
    title = StringField(default='')
    author = StringField(default='佚名', validators=[length(min=0, max=48, message='作者长度不能超过50字')])
    content = TextAreaField(default='')
    order_number = StringField()
    chars_sum = IntegerField()
    sum = IntegerField()
    taobao_orders = []
    file_path = StringField(default='')

    def __init__(self, g):
        super(ArticleSubmitByUploadForm, self).__init__()
        self.uid = g.user.uid

    def validate_order_number(self, field):
        if self.content.data == '':
            raise ValidationError('没有获取到内容，请重新提交')
        if self.chars_sum.data == 0:
            self.chars_sum.data = len(self.content.data)
        unit = 1000
        sum = math.floor(int(self.chars_sum.data) / unit)
        if sum == 0:
            sum = 1
        self.sum.data = sum
        pattern = '^\d{18,19}(,\d{18,19})*'
        if not re.fullmatch(pattern, field.data):
            raise ValidationError('订单号格式不正确,应为18或19位数字,不可包含空格,若有多个订单请用英文逗号分隔!')
        # secret = redisclient.getAppSecret(self.domain.data) if self.domain.data != '' else redisclient.getAppSecret(
        #     'check')
        self.taobao_orders = field.data.split(',') if ',' in field.data else [field.data]
        if len(set(self.taobao_orders)) != len(self.taobao_orders):
            raise ValidationError('请不要重复输入相同订单号哦。')
        order_status = Order_Status(field.data, self.sum.data, 'TbAldszyw2zfa35ttemzxhbh2zkx27x6mabxssreswt2vkxgxt',
                                    self.chars_sum.data)
        isvalid = order_status.validate_order_number('text_check')
        if isvalid == 9:
            self.free.data = 1


class DocUploadForm(FileBaseForm):
    file = FileField('file', validators=[FileRequired(message='请选择文件上传'),
                                         FileAllowed(['docx', 'doc'], message='仅允许上传docx,doc格式文件！'),
                                         ])
    content = StringField()
    filePath = StringField()
    char_sum = StringField()
    showfilename = StringField()

    def __init__(self, g):
        super(DocUploadForm, self).__init__()
        self.uid = g.user.uid

    def validate_file(self, field):
        file_name = field.data.filename.replace('+', '')
        timestamp = str(int(datetime.now().timestamp()))
        localPath = DOC_PATH + timestamp + '_' + file_name
        self.filePath.data = localPath
        field.data.save(localPath)
        if '.pdf' in file_name:
            char_sum, content = ParsePDF(timestamp + '_' + file_name)
        else:
            char_sum, content = ParseDoc(timestamp + '_' + file_name)
        self.char_sum.data = self.clean_content_count(content)
        self.content.data = self.clean_content(content)
        if self.content.data == '':
            raise ValidationError('doc文档读取失败，可能文件损坏，请检查后重新上传！')
        if len(self.content.data) < 100:
            raise ValidationError('字数不足100！不可检测')
        if len(self.content.data) > 300000:
            raise ValidationError('单次检测上限30万字，请修改或分批上传')

    def clean_content_count(self, content):
        java_string = 'Evaluation Warning: The document was created with Spire.Doc for JAVA.'
        return len(content.strip().replace(' ', '').replace('\n', '').replace('\r', '').replace(java_string, ''))

    def clean_content(self, content):
        java_string = 'Evaluation Warning: The document was created with Spire.Doc for JAVA.'
        return content.replace(java_string, '')


class WxSearchReport(SearchForm):
    task_status = StringField()
    start = IntegerField()
    user = IntegerField()

    def __init__(self, g):
        super(WxSearchReport, self).__init__()
        self.user.data = g.user.uid

    def validate_start(self, field):
        self.page.data = int(field.data / 10) + 1


class WxVerifyOrderNumberForm(Form):
    order_number = StringField()
    
class UnlockAigcNeedShareCountForm(Form):
    order_number = StringField()
    report_type = StringField()
    
class UnlockAigcByWxPay(Form):
    order_number = StringField()
    out_trade_no = StringField()
    amount = DecimalField()